﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;

using PlanningGIS.Util.Convertor;
using PlanningGIS.ArcGIS;
using PlanningGIS.Util.Log;
using PlanningGIS.Engine.Controls;

namespace PlanningGIS.DataCheck.model
{
    /// <summary>
    /// 水系线面名称不一致检查（对于明流河段（面）,运河（面）,干渠（面）或支渠（面），检查水系结构线的名称属性与对应的水系面的名称属性是否一致）
    /// </summary>
    public class HydPyLnNameCheck : Check
    {
        public int Check(string errType, IFeatureLayer pFeatLyrPy, IFeatureLayer pFeatLyrLn, IGeometry pGeometry,
            string whereClause, string fcodename, string fnamename,string suprivername)
        {
            IFeatureClass pFeatClsPy = pFeatLyrPy.FeatureClass;
            IFeatureClass pFeatClsLn = pFeatLyrLn.FeatureClass;

            if (pFeatClsLn.ShapeType != esriGeometryType.esriGeometryPolyline)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层不是线状图层，检查失败！");
                return -1;
            }

            if (pFeatClsPy.ShapeType != esriGeometryType.esriGeometryPolygon)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrPy.Name + "]图层不是面状图层，检查失败！");
                return -1;
            }

            int idxfcodepy = pFeatClsPy.FindField(fcodename);
            if (idxfcodepy == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrPy.Name + "]图层中未找到分类代码[" + fcodeName + "]字段，检查失败！");
                return -1;
            }

            int idxfcodeln = pFeatClsLn.FindField(fcodename);
            if (idxfcodeln == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层中未找到分类代码[" + fcodeName + "]字段，检查失败！");
                return -1;
            }

            int idxfnameln = pFeatClsLn.FindField(fnamename);
            if (idxfnameln == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层中未找到名称[" + fnamename + "]字段，检查失败！");
                return -1;
            }

            int idxfnamepy = pFeatClsPy.FindField(fnamename);
            if (idxfnamepy == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrPy.Name + "]图层中未找到名称[" + fnamename + "]字段，检查失败！");
                return -1;
            }

            int idxsupriver = pFeatClsLn.FindField(suprivername);
            if (idxsupriver == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层中未找到上级河流名[" + suprivername + "]字段，检查失败！");
                return -1;
            }

            ISpatialFilter pSpatialFileter = new SpatialFilterClass();
            if (pGeometry != null) pSpatialFileter.Geometry = pGeometry;

            string sql = fcodename + " in('210101500','220100500','220201500','220202500')";
            pSpatialFileter.WhereClause = whereClause == "" ? sql : whereClause + " and " + sql;

            pSpatialFileter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
            pSpatialFileter.GeometryField = pFeatClsPy.ShapeFieldName;

            showFakePro(true);
            LogHelper.WriteLog("正在计算需要检查的要素数目...");

            int max = FeatureClassHelper.GetFeatureCountFromLayer(pFeatLyrPy, pSpatialFileter);

            LogHelper.WriteLog("计算完毕。共有" + max + "个要素参与检查。");
            showFakePro(false);

            if (max == 0)
            {
                LogHelper.WriteLog("没有满足检查要求的要素存在。");
                return -1;
            }

            setProcessBarMax(max);

            IFeatureCursor pFeatCur;
            pFeatCur = pFeatLyrPy.Search(pSpatialFileter, false);

            IFeature pFeaturePy;

            int count = 0;
            int errCount = 0;

            while ((pFeaturePy = pFeatCur.NextFeature()) != null)
            {
                if (IsStop()) break;

                setProcessBarCurrent(count);
                count++;

                string fnamevaluepy = StringHelper.ConvertWRTNull(pFeaturePy.get_Value(idxfnamepy));
                if (fnamevaluepy == "0" || fnamevaluepy == " ") fnamevaluepy = "";

                IPolygon pPolygon = pFeaturePy.ShapeCopy as IPolygon ;
                ITopologicalOperator2 pTop = pPolygon as ITopologicalOperator2;
                pTop.IsKnownSimple_2 = false;
                pTop.Simplify();
                IRelationalOperator pRel = pPolygon as IRelationalOperator;

                IFeatureCursor pFeatCurLn = CursorHelper.GetCursor(pFeatClsLn, pPolygon, fcodename + " = '260801416'");
                IFeature pFeatureLn = pFeatCurLn.NextFeature();

                while (pFeatureLn != null)
                {
                    string fnamevalueln = StringHelper.ConvertWRTNull(pFeatureLn.get_Value(idxfnameln));
                    if (fnamevalueln == "0" || fnamevalueln == " ") fnamevalueln = "";
                    string suprivervalue = StringHelper.ConvertWRTNull(pFeatureLn.get_Value(idxsupriver));
                    if (suprivervalue == "0" || suprivervalue == " ") suprivervalue = "";

                    if (fnamevaluepy != fnamevalueln && fnamevaluepy != suprivervalue)
                    {
                        IGeometry pGeoRst = pTop.Intersect(pFeatureLn.ShapeCopy, esriGeometryDimension.esriGeometry1Dimension);
                        if (pGeoRst != null && !pGeoRst.IsEmpty)
                        {
                            RecordListHelper.AddRecordItem(errType, pFeatLyrPy, pFeatLyrLn, pFeaturePy, pFeatureLn, pGeoRst, "");
                            errCount++;
                        }
                    }

                    pFeatureLn = pFeatCurLn.NextFeature();
                }

                DataCheckUtility.ReleaseComObject(pFeatCurLn);
            }

            finishPro.Invoke();

            DataCheckUtility.ReleaseComObject(pFeaturePy);
            DataCheckUtility.ReleaseComObject(pFeatCur);

            LogHelper.WriteLog("水系线面名称不一致检查结束。共发现" + errCount + "处错误！\n");

            return errCount;
        }
    }
}
